package com.googlecode.monitoring.db.service;

import com.googlecode.monitoring.config.SpringApplicationContext;
import com.googlecode.monitoring.db.dao.TableReaderDao;
import com.googlecode.monitoring.db.model.DbItemToCheck;
import com.googlecode.monitoring.db.model.MaxAgeOfData;
import com.googlecode.monitoring.db.model.TableOfData;
import com.googlecode.monitoring.model.ItemToCheck;
import com.googlecode.monitoring.model.StateName;
import com.googlecode.monitoring.service.MonitoringService;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;


@Service(value = "monitoringService")
public class DbMonitoringService implements MonitoringService {

	Logger log = Logger.getLogger(DbMonitoringService.class);
	private TableReaderDao tableReaderDao;


	public boolean checkIsItemOutdated(ItemToCheck item) {
        DbItemToCheck dbItem = (DbItemToCheck) item;
		TableOfData table = dbItem.getTable();
		MaxAgeOfData ageOfData = dbItem.getMaxAgeOfData();
		dbItem.switchState(StateName.CHECKED);
        dbItem.setLastCheckTime(new DateTime());
        tableReaderDao = SpringApplicationContext.getBean("tableReaderDao_"+ dbItem.getDataSourceItem().getBeanName(), TableReaderDao.class);
		if (table.getColumnName() == null) {
			int count = tableReaderDao.getLatestDate(table.getName());
			log.debug("table " + table.getName() + "; count =" + count);
			return !(count > 0); // if data exists
		}
		List<Date> latestDates = tableReaderDao.getLatestDate(table.getName(), table.getColumnName());
		for (Date latestDate : latestDates) {
			log.debug("table " + table.getName() + " latest date =" + latestDate);
			Calendar latestCalendar = Calendar.getInstance();
			latestCalendar.setTime(latestDate);
			return !ageOfData.isValid(latestCalendar);
		}
		return true;// outdated
	}
}
